<script setup lang="ts">
// 加载图书数据
import { getBookList } from '@/api/book'

import { onMounted, ref } from 'vue' 
import { onShow } from '@dcloudio/uni-app'

// 搜索关键词
const searchKeyword = ref('')

// 分类数据
const categories = ref([
  { id: 1, name: '文学' },
  { id: 2, name: '科技' },
  { id: 3, name: '历史' },
  { id: 4, name: '艺术' },
])

// 当前选中的分类
const currentCategory = ref(0)

// 图书列表数据
const books = ref([

])

// 是否还有更多数据
const hasMore = ref(true)

// 页码
const page = ref(1)

// 搜索处理（优化后）
function handleSearch() {
  page.value = 1;
  uni.showLoading({ title: '搜索中...' }); // 添加加载提示
  loadBooks();
}

// 加载图书数据（优化后）
async function loadBooks() {
  try {
    const params = {
      keyword: searchKeyword.value,
      page: page.value,
      ...(currentCategory.value !== 0 ? { category: currentCategory.value } : {})
    };
    const res = await getBookList(params);
    books.value = res.data.list;
    hasMore.value = res.data.length === 10; // 假设后端返回单页10条数据时表示有更多
  } catch (error) {
    uni.showToast({ title: '加载失败', icon: 'none' });
  } finally {
    uni.hideLoading(); // 无论成功/失败都关闭加载提示
  }
}

// 选择分类
function selectCategory(categoryId: number) {
  currentCategory.value = categoryId
  page.value = 1
  loadBooks()
}

// 获取状态文本
function getStatusText(status: string) {
  const statusMap = {
    available: '可借阅',
    borrowed: '已借出',
    reserved: '已预约',
  }
  return statusMap[status] || status
}

// 跳转到详情页
function goToDetail(bookId: number) {
  uni.navigateTo({
    url: `/pages/book/detail/index?id=${bookId}`,
  })
}

// 加载更多
function loadMore() {
  if (!hasMore.value)
    return
  page.value++
  loadBooks()
}

// 页面加载时获取数据
onMounted(() => {
  loadBooks()
})

// 页面显示时刷新数据（包括从搜索页返回的场景）
onShow(() => {
  // 读取临时存储的搜索关键词
  const searchKeywordFromStorage = uni.getStorageSync('currentSearchKeyword')
  if (searchKeywordFromStorage) {
    // 更新搜索关键词并触发搜索
    searchKeyword.value = searchKeywordFromStorage
    // 清空临时存储（避免重复触发）
    uni.removeStorageSync('currentSearchKeyword')
    handleSearch() // 调用搜索方法加载数据
  }
  loadBooks();
})
</script>

<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <input
        v-model="searchKeyword"
        type="text"
        placeholder="搜索图书"
        @confirm="handleSearch"
      >
    </view>

    <!-- 筛选栏 -->
    <view class="filter-bar">
      <view class="filter-item" :class="{ active: currentCategory === 0 }" @click="selectCategory(0)">
        全部
      </view>
      <view
        v-for="item in categories"
        :key="item.id"
        class="filter-item"
        :class="{ active: currentCategory === item.id }"
        @click="selectCategory(item.id)"
      >
        {{ item.name }}
      </view>
    </view>

    <!-- 图书列表 -->
    <view class="book-list">
      <view v-for="book in books" :key="book.id" class="book-item" @click="goToDetail(book.id)">
        <image :src="book.cover" mode="aspectFill" class="book-cover"/>
        <view class="book-info">
          <text class="book-title">
            {{ book.title }}
          </text>
          <text class="book-author">
            {{ book.author }}
          </text>
          <text class="book-desc">
            {{ book.description }}
          </text>
          <view class="book-meta">
            <text class="book-status" :class="book.status">
              {{ getStatusText(book.status) }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="books.length === 0" class="empty-tip">
      <text>暂无相关图书</text>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore" class="load-more" @click="loadMore">
      <text>加载更多</text>
    </view>
  </view>
</template>

<style lang="scss">
.container {
  padding: 20rpx;
}

.search-bar {
  padding: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  width: 88%;

  input {
    width: 100%;
    height: 72rpx;
    background: #f5f5f5;
    border-radius: 36rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
  }
}

.filter-bar {
  display: flex;
  background: #fff;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow-x: auto;

  .filter-item {
    padding: 10rpx 30rpx;
    font-size: 28rpx;
    color: #666;
    background: #f5f5f5;
    border-radius: 28rpx;
    margin-right: 20rpx;
    white-space: nowrap;

    &.active {
      color: #fff;
      background: #4caf50;
    }
  }
}

.book-list {
  .book-item {
    display: flex;
    padding: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;

    .book-cover {
      width: 200rpx;
      height: 280rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .book-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .book-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }

      .book-author {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 10rpx;
      }

      .book-desc {
        font-size: 26rpx;
        color: #999;
        margin-bottom: 20rpx;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }

      .book-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .book-status {
          font-size: 24rpx;
          padding: 4rpx 12rpx;
          border-radius: 4rpx;

          &.available {
            background: #e8f5e9;
            color: #4caf50;
          }

          &.borrowed {
            background: #fff3e0;
            color: #ff9800;
          }

          &.reserved {
            background: #e3f2fd;
            color: #2196f3;
          }
        }

        .book-distance {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

.empty-tip {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  margin-top: 200rpx;
}

.load-more {
  text-align: center;
  padding: 30rpx 0;
  color: #666;
  font-size: 28rpx;
}
</style>
